
from main import db
from sqlalchemy.exc import InvalidRequestError
from main.utils import JSONHelper
from datetime import datetime
from sqlalchemy import or_, and_, func
from main.models import Questionnaire, Option, QuestionnaireCommit


def insert(object):
    try:
        if type(object) == list:
            for i in object:
                i.time = datetime.now()
                db.session.add(i)
        else:
            object.time = datetime.now()
            db.session.add(object)
        db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False


def update(object):
    try:
        object.time = datetime.now()
        db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False

def query_questionnaire():
    '''
    query all questionnaire
    :return: questionnaire
    '''
    return Questionnaire.query.all()


def query_option_by_question_id(question_id):
    '''
    query question option by question_id
    :param question_id:
    :return: question option
    '''
    return Option.query.filter(Option.question_id == question_id).all()


def query_questionnaire_commit_by_user_id(user_id):
    '''
    query questionnaire commit by user_id
    :param user_id:
    :return: all questionnaire commit
    '''
    return QuestionnaireCommit.query.filter(QuestionnaireCommit.user_id == user_id).all()

def delete(object):
    try:
        if type(object) == list:
            for o in object:
                db.session.delete(o)
                db.session.commit()
            else:
                db.session.delete(object)
                db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False


def query():
    return QuestionnaireCommit.query.all()

if __name__ == '__main__':
    for i in query():
        print(i.to_json())